package com.example.demo.controller;

import com.example.demo.mapper.EmployeeMapper;
import com.example.demo.pojo.Employee;
import com.example.demo.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
    
    @Autowired
    private EmployeeMapper employeeMapper;
    
    // 查询所有员工（支持分页和关键字搜索）
    @GetMapping("/findAll")
    public Result findAll(@RequestParam(value = "keyword", required = false, defaultValue = "") String keyword,
                         @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                         @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Employee> list = employeeMapper.findAll(keyword);
        PageInfo<Employee> pageInfo = new PageInfo<>(list);
        return new Result(200, "查询成功", pageInfo);
    }
    
    // 根据ID查询员工
    @GetMapping("/findById")
    public Result findById(int id) {
        Employee employee = employeeMapper.findById(id);
        return new Result(200, "查询成功", employee);
    }
    
    // 新增员工
    @PostMapping("/save")
    public Result saveEmployee(@RequestBody Employee employee) {
        int result = employeeMapper.saveEmployee(employee);
        if (result > 0) {
            return new Result(200, "添加成功", result);
        } else {
            return new Result(400, "添加失败", null);
        }
    }
    
    // 更新员工
    @PostMapping("/update")
    public Result updateEmployee(@RequestBody Employee employee) {
        int result = employeeMapper.updateEmployee(employee);
        if (result > 0) {
            return new Result(200, "更新成功", result);
        } else {
            return new Result(400, "更新失败", null);
        }
    }
    
    // 删除员工
    @GetMapping("/delete")
    public Result deleteEmployee(int id) {
        int result = employeeMapper.deleteEmployee(id);
        if (result > 0) {
            return new Result(200, "删除成功", result);
        } else {
            return new Result(400, "删除失败", null);
        }
    }
    
    // 根据部门ID查询员工
    @GetMapping("/findByDeptId")
    public Result findByDeptId(int deptId) {
        List<Employee> list = employeeMapper.findByDeptId(deptId);
        return new Result(200, "查询成功", list);
    }
}